package chapter04.sync;

import lombok.extern.slf4j.Slf4j;

// 三个线程顺序输出abcabcabcabcabc
@Slf4j
public class ABCTest1 {
    private static final Object lock1=new Object();
    private static final Object lock2=new Object();
    private static final Object lock3=new Object();
    private static  boolean flag1=false;
    private static  boolean flag2=false;
    private static boolean flag3=true;
    public static void main(String[] args) throws InterruptedException {

        Thread t1 = new Thread(() -> {
            for(int i=1;i<=5;i++){
                synchronized (lock3){
                    while (!flag3){
                        try {
                            lock3.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    synchronized (lock1){
                        System.out.printf("a");
                        flag1=true;
                        lock1.notifyAll();
                    }
                    flag3=false;
                }
            }
        }, "t1");

        Thread t2 = new Thread(() -> {
            for(int i=1;i<=5;i++){
                synchronized (lock1){
                    while (!flag1){
                        try {
                            lock1.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    synchronized (lock2){
                        System.out.printf("b");
                        flag2=true;
                        lock2.notifyAll();
                    }
                    flag1=false;
                }
            }
        }, "t2");

        Thread t3 = new Thread(() -> {
            for(int i=1;i<=5;i++){
                synchronized (lock2){
                    while (!flag2){
                        try {
                            lock2.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                    synchronized (lock3){
                        System.out.printf("c");
                        flag2=false;
                        flag3=true;
                        lock3.notifyAll();
                    }

                }
            }
        }, "t3");

        t1.start();
        t2.start();
        t3.start();
    }
}
